import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Chip,
  Button,
  Tooltip,
  TextField,
  InputAdornment,
  Switch,
  FormControlLabel,
  Alert,
  CircularProgress,
  TablePagination,
} from '@mui/material';
import {
  PlayArrow as StartIcon,
  Stop as StopIcon,
  PowerSettingsNew as ForceStopIcon,
  Refresh as RebootIcon,
  Pause as SuspendIcon,
  PlayCircle as ResumeIcon,
  Visibility as ViewIcon,
  Computer as ConsoleIcon,
  Delete as DeleteIcon,
  Search as SearchIcon,
  Add as AddIcon,
} from '@mui/icons-material';
import { useConnectionStore } from '../../stores/connectionStore';
import { useDomainStore } from '../../stores/domainStore';
import domainService from '../../services/domains';
import { DomainState } from '../../types/api';
import type { DomainStateType, DomainOperation } from '../../types/api';

const DomainList: React.FC = () => {
  const navigate = useNavigate();
  const currentConnection = useConnectionStore(state => state.currentConnection);
  const connections = useConnectionStore(state => state.connections);
  const { fetchDomains, performDomainOperation, domains, loading, error, clearError } = useDomainStore();
  
  const [searchTerm, setSearchTerm] = useState('');
  const [includeInactive, setIncludeInactive] = useState(true);
  const [operationLoading, setOperationLoading] = useState<string | null>(null);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  // 获取虚拟机列表
  useEffect(() => {
    if (currentConnection) {
      // 检查当前连接是否有效
      const isValidConnection = connections.some(conn => conn.name === currentConnection);
      if (isValidConnection) {
        fetchDomains(currentConnection, includeInactive);
      }
    }
  }, [currentConnection, includeInactive, connections]);

  // 清除错误
  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => clearError(), 5000);
      return () => clearTimeout(timer);
    }
  }, [error, clearError]);

  // 过滤虚拟机
  const filteredDomains = domains.filter(domain =>
    domain.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    domain.uuid.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 分页处理函数
  const handleChangePage = (_event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  // 获取状态颜色
  const getStateColor = (state: DomainStateType) => {
    switch (state) {
      case DomainState.RUNNING:
        return 'success';
      case DomainState.SHUTOFF:
        return 'default';
      case DomainState.PAUSED:
        return 'warning';
      case DomainState.SUSPENDED:
        return 'info';
      case DomainState.CRASHED:
        return 'error';
      default:
        return 'default';
    }
  };

  // 获取状态显示文本
  const getStateText = (state: DomainStateType) => {
    switch (state) {
      case DomainState.RUNNING:
        return '运行中';
      case DomainState.SHUTOFF:
        return '已关机';
      case DomainState.PAUSED:
        return '已暂停';
      case DomainState.SUSPENDED:
        return '已挂起';
      case DomainState.CRASHED:
        return '已崩溃';
      default:
        return '未知';
    }
  };

  // 执行虚拟机操作
  const handleDomainOperation = async (domainName: string, operation: DomainOperation) => {
    if (!currentConnection) return;
    
    // 检查连接是否仍然有效
    const isValidConnection = connections.some(conn => conn.name === currentConnection);
    if (!isValidConnection) {
      // 连接无效，显示错误信息
      clearError();
      // 可以考虑重新获取连接列表或显示错误信息
      return;
    }
    
    setOperationLoading(`${operation}-${domainName}`);
    try {
      await performDomainOperation(currentConnection, domainName, operation);
    } catch (error) {
      console.error(`虚拟机操作 ${operation} 失败:`, error);
    } finally {
      setOperationLoading(null);
    }
  };

  // 检查操作是否可用
  const isOperationEnabled = (domain: any, operation: DomainOperation) => {
    switch (operation) {
      case 'start':
        return domain.state === DomainState.SHUTOFF || domain.state === DomainState.SUSPENDED;
      case 'shutdown':
      case 'force-stop':
      case 'suspend':
        return domain.state === DomainState.RUNNING;
      case 'reboot':
        return domain.state === DomainState.RUNNING;
      case 'resume':
        return domain.state === DomainState.PAUSED;
      default:
        return false;
    }
  };

  if (!currentConnection) {
    return (
      <Box>
        <Typography variant="h4" component="h1" gutterBottom fontWeight="bold">
          虚拟机管理
        </Typography>
        <Alert severity="warning">
          请先选择一个连接
        </Alert>
      </Box>
    );
  }

  // 检查当前连接是否有效
  const isValidConnection = connections.some(conn => conn.name === currentConnection);
  if (!isValidConnection) {
    return (
      <Box>
        <Typography variant="h4" component="h1" gutterBottom fontWeight="bold">
          虚拟机管理
        </Typography>
        <Alert severity="warning">
          当前选择的连接已不存在，请重新选择连接
        </Alert>
      </Box>
    );
  }

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h4" component="h1" fontWeight="bold">
          虚拟机管理
        </Typography>
        <Box display="flex" gap={2}>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => navigate('/domains/create')}
            sx={{ bgcolor: 'primary.main', color: 'white' }}
          >
            创建虚拟机
          </Button>
        </Box>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={clearError}>
          {error}
        </Alert>
      )}

      <Paper sx={{ p: 2, mb: 2 }}>
        <Box display="flex" gap={2} alignItems="center" flexWrap="wrap">
          <TextField
            placeholder="搜索虚拟机..."
            variant="outlined"
            size="small"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
            sx={{ minWidth: 300 }}
          />
          <FormControlLabel
            control={
              <Switch
                checked={includeInactive}
                onChange={(e) => setIncludeInactive(e.target.checked)}
              />
            }
            label="显示非活动虚拟机"
          />
        </Box>
      </Paper>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow sx={{ bgcolor: 'grey.50' }}>
              <TableCell>名称</TableCell>
              <TableCell>UUID</TableCell>
              <TableCell>状态</TableCell>
              <TableCell align="center">vCPUs</TableCell>
              <TableCell align="center">内存</TableCell>
              <TableCell align="center">操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={6} align="center">
                  <CircularProgress />
                </TableCell>
              </TableRow>
            ) : filteredDomains.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} align="center">
                  <Typography color="text.secondary">
                    {searchTerm ? '未找到匹配的虚拟机' : '暂无虚拟机'}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              filteredDomains.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((domain) => (
                <TableRow key={domain.uuid} hover>
                  <TableCell>
                    <Typography fontWeight="medium">{domain.name}</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" color="text.secondary">
                      {domain.uuid}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={getStateText(domain.state as DomainStateType)}
                      color={getStateColor(domain.state as DomainStateType)}
                      size="small"
                    />
                  </TableCell>
                  <TableCell align="center">{domain.vcpus || '-'}</TableCell>
                  <TableCell align="center">
                    {domain.memory ? `${Math.round(domain.memory / 1024)} GB` : '-'}
                  </TableCell>
                  <TableCell align="center">
                    <Box display="flex" gap={1} justifyContent="center">
                      {/* 启动 */}
                      <Tooltip title="启动">
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => handleDomainOperation(domain.name, 'start')}
                            disabled={!isOperationEnabled(domain, 'start') || operationLoading === `start-${domain.name}`}
                            sx={{
                              '&.Mui-disabled': {
                                opacity: 0.5,
                                cursor: 'not-allowed',
                              }
                            }}
                          >
                            {operationLoading === `start-${domain.name}` ? (
                              <CircularProgress size={20} />
                            ) : (
                              <StartIcon color={isOperationEnabled(domain, 'start') ? "success" : "disabled"} />
                            )}
                          </IconButton>
                        </span>
                      </Tooltip>

                      {/* 关机 */}
                      <Tooltip title="关机">
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => handleDomainOperation(domain.name, 'shutdown')}
                            disabled={!isOperationEnabled(domain, 'shutdown') || operationLoading === `shutdown-${domain.name}`}
                            sx={{
                              '&.Mui-disabled': {
                                opacity: 0.5,
                                cursor: 'not-allowed',
                              }
                            }}
                          >
                            {operationLoading === `shutdown-${domain.name}` ? (
                              <CircularProgress size={20} />
                            ) : (
                              <StopIcon color={isOperationEnabled(domain, 'shutdown') ? "action" : "disabled"} />
                            )}
                          </IconButton>
                        </span>
                      </Tooltip>

                      {/* 强制停止 */}
                      <Tooltip title="强制停止">
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => handleDomainOperation(domain.name, 'force-stop')}
                            disabled={!isOperationEnabled(domain, 'force-stop') || operationLoading === `force-stop-${domain.name}`}
                            sx={{
                              '&.Mui-disabled': {
                                opacity: 0.5,
                                cursor: 'not-allowed',
                              }
                            }}
                          >
                            {operationLoading === `force-stop-${domain.name}` ? (
                              <CircularProgress size={20} />
                            ) : (
                              <ForceStopIcon color={isOperationEnabled(domain, 'force-stop') ? "error" : "disabled"} />
                            )}
                          </IconButton>
                        </span>
                      </Tooltip>

                      {/* 重启 */}
                      <Tooltip title="重启">
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => handleDomainOperation(domain.name, 'reboot')}
                            disabled={!isOperationEnabled(domain, 'reboot') || operationLoading === `reboot-${domain.name}`}
                            sx={{
                              '&.Mui-disabled': {
                                opacity: 0.5,
                                cursor: 'not-allowed',
                              }
                            }}
                          >
                            {operationLoading === `reboot-${domain.name}` ? (
                              <CircularProgress size={20} />
                            ) : (
                              <RebootIcon color={isOperationEnabled(domain, 'reboot') ? "primary" : "disabled"} />
                            )}
                          </IconButton>
                        </span>
                      </Tooltip>

                      {/* 暂停 */}
                      <Tooltip title="暂停">
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => handleDomainOperation(domain.name, 'suspend')}
                            disabled={!isOperationEnabled(domain, 'suspend') || operationLoading === `suspend-${domain.name}`}
                            sx={{
                              '&.Mui-disabled': {
                                opacity: 0.5,
                                cursor: 'not-allowed',
                              }
                            }}
                          >
                            {operationLoading === `suspend-${domain.name}` ? (
                              <CircularProgress size={20} />
                            ) : (
                              <SuspendIcon color={isOperationEnabled(domain, 'suspend') ? "action" : "disabled"} />
                            )}
                          </IconButton>
                        </span>
                      </Tooltip>

                      {/* 恢复 */}
                      <Tooltip title="恢复">
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => handleDomainOperation(domain.name, 'resume')}
                            disabled={!isOperationEnabled(domain, 'resume') || operationLoading === `resume-${domain.name}`}
                            sx={{
                              '&.Mui-disabled': {
                                opacity: 0.5,
                                cursor: 'not-allowed',
                              }
                            }}
                          >
                            {operationLoading === `resume-${domain.name}` ? (
                              <CircularProgress size={20} />
                            ) : (
                              <ResumeIcon color={isOperationEnabled(domain, 'resume') ? "success" : "disabled"} />
                            )}
                          </IconButton>
                        </span>
                      </Tooltip>

                      {/* 查看详情 */}
                      <Tooltip title="查看详情">
                        <IconButton
                          size="small"
                          onClick={() => navigate(`/domains/${domain.name}`)}
                        >
                          <ViewIcon color="info" />
                        </IconButton>
                      </Tooltip>

                      {/* 控制台 */}
                      <Tooltip title="控制台">
                        <IconButton
                          size="small"
                          onClick={() => navigate(`/domains/${domain.name}/console`)}
                          disabled={domain.state !== DomainState.RUNNING}
                          sx={{
                            '&.Mui-disabled': {
                              opacity: 0.5,
                              cursor: 'not-allowed',
                            }
                          }}
                        >
                          <ConsoleIcon color={domain.state === DomainState.RUNNING ? "action" : "disabled"} />
                        </IconButton>
                      </Tooltip>

                      {/* 删除 */}
                      <Tooltip title="删除">
                        <IconButton
                          size="small"
                          onClick={() => {
                            if (window.confirm(`确定要删除虚拟机 "${domain.name}" 吗？`)) {
                              domainService.deleteDomain(currentConnection, domain.name)
                                .then(() => fetchDomains(currentConnection, includeInactive))
                                .catch((error: any) => console.error('删除虚拟机失败:', error));
                            }
                          }}
                          disabled={domain.state === DomainState.RUNNING || operationLoading === `delete-${domain.name}`}
                          sx={{
                            '&.Mui-disabled': {
                              opacity: 0.5,
                              cursor: 'not-allowed',
                            }
                          }}
                        >
                          {operationLoading === `delete-${domain.name}` ? (
                            <CircularProgress size={20} />
                          ) : (
                            <DeleteIcon color={(domain.state !== DomainState.RUNNING && operationLoading !== `delete-${domain.name}`) ? "error" : "disabled"} />
                          )}
                        </IconButton>
                      </Tooltip>
                    </Box>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>
      
      <TablePagination
        component="div"
        count={filteredDomains.length}
        page={page}
        onPageChange={handleChangePage}
        rowsPerPage={rowsPerPage}
        onRowsPerPageChange={handleChangeRowsPerPage}
        rowsPerPageOptions={[5, 10, 25, 50]}
        labelRowsPerPage="每页行数:"
        labelDisplayedRows={({ from, to, count }) => 
          `${from}-${to} 共 ${count} 条`
        }
      />
    </Box>
  );
};

export default DomainList;